package com.xk.blog.controller.admin;

import java.util.List;

import javax.annotation.Resource;

import com.xk.blog.common.JsonResult;
import com.xk.blog.controller.BaseController;
import com.xk.blog.entity.Linkman;
import com.xk.blog.service.LinkmanService;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/admin/linkman")
public class LinkmanController extends BaseController {

    @Resource
    private LinkmanService linkmanService;

    @GetMapping("/index")
    public String index() {
        return "admin/linkman/index";
    }
    
    @GetMapping("/view")
    public String view(ModelMap map) {
        List<Linkman> list = linkmanService.findAllMan();
        map.put("list", list);
        return "admin/linkman/view";
    }

    @PostMapping("/list")
    @ResponseBody
    public Page<Linkman> list() {
        PageRequest pageRequest = getPageRequest();
        Page<Linkman> page = linkmanService.findAll(pageRequest);
        return page;
    }

    @GetMapping("/form")
    public String form(@RequestParam(required = false) Long id, ModelMap map) {
        if (id != null) {
            Linkman linkman = linkmanService.findById(id);
            map.put("linkman", linkman);
        }
        return "admin/linkman/form";
    }

    @PostMapping("/save")
    @ResponseBody
    public JsonResult save(Linkman linkman) {
        try {
            if (linkman != null) {
                linkman.setStatus(0);
                linkmanService.saveOrUpdate(linkman);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.fail(e.getMessage());
        }
        return JsonResult.ok();
    }

    @PostMapping("/{id}/del")
    @ResponseBody
    public JsonResult delete(@PathVariable Long id) {
        try {
            linkmanService.delete(id);
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.fail(e.getMessage());
        }
        return JsonResult.ok();
    }

}
